package com.lucenex.bean;



import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.search.highlight.Highlighter;
import com.ld.ThreadPool.LoggerFactory;
/**
 * bean 控制类
 * @author zxw
 *
 */
public class BeanConfig{

	private Logger log = LoggerFactory.getLogger(BeanConfig.class);
	//词库
	private Map<String, Dic> dicConfig = new HashMap<>();

	//高亮 value 格式 {method:method,object:object}
	private Map<String, Map<String, Object>> highlightConfig = new HashMap<>();
	static BeanConfig config = new BeanConfig();


	/**
	 * 初始化bean容器
	 * @return
	 */
	public static BeanConfig build() {
		synchronized(config) {
			return config;
		}
	}

	/**
	 * 添加
	 * @param plugin
	 */
	public void add(Plugin plugin) {
		Class<? extends Plugin> clas = plugin.getClass();
		Method[] methods = clas.getMethods();
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			BeanKey beanKey = method.getAnnotation(BeanKey.class);
			if(!method.isAnnotationPresent(BeanKey.class) || beanKey == null) {//该方法不是 bean 或 没有 值
				continue;
			}
			String dataSourceKey = beanKey.value();
			String typeName = method.getAnnotatedReturnType().getType().getTypeName();
			if(typeName.equals(Dic.class.getName())) {//该方法是 词库
				try {
					Dic dic = (Dic) method.invoke(plugin);

					dic.init();
					dicConfig.put(dataSourceKey, dic);
				} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
					log.log(Level.SEVERE, "BaseConfig add plugin error", e);
				}
			}else if(typeName.equals(Highlighter.class.getName())) {//高亮
				Map<String, Object> map = new HashMap<>();
				map.put("method", method);
				map.put("object", plugin);
				highlightConfig.put(dataSourceKey, map);
			}

		}
	}

	/**
	 * 获取一个词库
	 * @param dataSourceKey
	 * @return
	 */
	public Dic getDic(String dataSourceKey) {
		return dicConfig.get(dataSourceKey);
	}

	/**
	 * 获取一个高亮
	 * @param dataSourceKey
	 * @return
	 */
	public Map<String, Object> getHigh(String dataSourceKey){
		return highlightConfig.get(dataSourceKey);
	}
}
